/**
 * weapp-js v2.2.3(2022-4-26)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2022 Motigo, Inc.
 *
 */
import BaseRequest from './base_request.js';
import Request from './request';
import File from './file';
import Log from 'log';
import Ad from './ad.js';
import Session from './session.js';
import Ui from './ui.js';
import Audio from './audio.js';
import Preload from './preload.js';
import Theme from './theme';
import Payment from './payment.js';
import CheckApp from './utils/check_app';
import Callback from './utils/callback.js';
import Util from './utils/util';

import { promisifyAll } from './polyfill/promisify.js';

// const ENV = 'release';

class Mox extends Callback {
    constructor() {
        super();
        this._ready = false;

        this.request = Request;
        this.session = Session;
        this.file = File;
        this.audio = Audio;
        this.preload = Preload;
        this.payment = Payment;
        this.ad = Ad;
        this.log = Log;
        this.theme = Theme;
        this.util = Util;
        this.user = Session.user;

        // 设置 appid
        const accountInfo = wx.getAccountInfoSync();
        this.appid = accountInfo.miniProgram.appId;
        this.session.init(this.appid);
        BaseRequest.appid = this.appid;

        // 线上包 默认统计 pvuv
        // if (ENV === 'release') {
        //     this.stat({
        //         key: '__visit__',
        //         uid: this.user.unionid || this.user.openid || ''
        //     });
        // }
    }
    /**
     * mox init
     *
     * @param {boolean} polyfill 是否支持 promise 写法
     *
     *
     */

    init(polyfill) {
        if (polyfill) {
            promisifyAll(this);
        } else {
            // ignore
        }
    }

    login = Session.login.bind(Session);
    createOrder = Payment.createOrder.bind(Payment);

    cloudRequest(opts = {}) {
        if (this._checkCloudRequestOpts(opts)) {
            wx.cloud
                .callFunction({
                    name: opts.name,
                    data: {
                        ...opts.data
                    }
                })
                .then(res => {
                    this.success(opts, res.result);
                })
                .catch(err => {
                    console.log(err);
                    wx.hideLoading();
                    if (opts.showModal) {
                        wx.showModal({
                            title: '',
                            content: `${JSON.stringify(err.toString())}`,
                            showCancel: false
                        });
                    }
                    this.fail(opts, {
                        msg: err
                    });
                });
        }
    }

    _checkCloudRequestOpts(opts) {
        if (!opts.data) {
            opts.data = {};
            return true;
        }
        if (!opts.name) {
            this.fail(opts, { msg: '云函数名称不能为空' });
            return false;
        }
    }

    stat(opts) {
        // 兼容只传 string 模式
        if (typeof opts === 'string') {
            opts = {
                key: opts
            };
        }
        setTimeout(() => {
            BaseRequest.post(`/data_analytics/pvuv/weapp_${this.appid}`, {
                key: opts.key,
                // uid: this.user.unionid,
                uid: opts.uid || this.user.unionid || this.user.openid || '',
                elapsed_time: opts.elapsed_time || 0
            })
                .then(res => {
                    // this.success(opts, res);
                })
                .catch(err => {
                    // if (err === 'OK') {
                    //     // 为了兼容 stat 接口直接返回 OK 的情况
                    //     this.success(opts);
                    // } else {
                    //     this.fail(opts, err);
                    // }
                });
        }, 10);
    }

    updateApp() {
        CheckApp.checkAppUpdateAndApply();
    }
}

let mox = new Mox();

export default mox;
